package logic

import (
	"context"
	"fmt"
	"mycrm/model/mysql"
	"mycrm/model/redisinit"
	"mycrm/pkg"

	"mycrm/mycrmrpc/internal/svc"
	"mycrm/mycrmrpc/mycrmrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *mycrmrpc.RegisterRequest) (*mycrmrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := redisinit.Client.Get("SendSms" + in.Mobile + "Register").Result()
	if in.SendSms != result {
		return nil, fmt.Errorf("短信验证失败,请重新输入")
	}

	result1, _ := redisinit.Client.Get("CaptCha" + in.Mobile + "Register").Result()
	if in.CaptCha != result1 {
		return nil, fmt.Errorf("图形验证失败,请重新输入")
	}

	var mycrm mysql.Mycrm

	mysql.DB.Debug().Where("mobile =?", in.Mobile).Find(&mycrm)

	if mycrm.ID != 0 {
		return nil, fmt.Errorf("手机号重复")
	}

	if pkg.MD5(mycrm.Password) != in.Password {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}

	m := mysql.Mycrm{
		Mobile:   mycrm.Mobile,
		Password: mycrm.Password,
	}
	mysql.DB.Create(&m)
	return &mycrmrpc.RegisterResponse{
		Id: int64(mycrm.ID),
	}, nil
}
